package services

import (
	"github.com/astaxie/beego/validation"
	"github.com/gin-gonic/gin"
	"net/http"
	"xwWechatPublic/middleware/app"
	"xwWechatPublic/utils/encryption"
	"xwWechatPublic/utils/logging"
)

type Auth struct {
	Username string `valid:"Required; MaxSize(50)"`
	Password string `valid:"Required; MaxSize(50)"`
}

//校验用户是否存在，并获取用户信息
func (a *Auth) Check() (bool, error) {
	//return CheckAuth(a.Username, a.Password)
	if a.Username == "admin" && a.Password == "123123" {
		return true, nil
	}
	return false, nil
}

// @Summary Get Auth
// @Produce  json
// @Param username query string true "userName"
// @Param password query string true "password"
// @Success 200 {object} app.Response
// @Failure 500 {object} app.Response
// @Router /auth [get]
func PostAuth(c *gin.Context) {
	appG := app.Gin{C: c}
	logging.Info("Post Auth ...")

	valid := validation.Validation{}
	username := c.Query("username")
	password := c.Query("password")

	a := Auth{Username: username, Password: password}
	logging.Debug("a[%v]", a)
	ok, _ := valid.Valid(&a)

	if !ok {
		logging.Error("校验失败[%v]!", valid.Errors)
		app.MarkErrors(valid.Errors)
		logging.Error("bad ...")
		appG.Response(http.StatusBadRequest, app.INVALID_PARAMS, nil)
		return
	}
	logging.Info("校验成功...")
	authService := Auth{Username: username, Password: password}
	isExist, err := authService.Check()
	if err != nil {
		appG.Response(http.StatusInternalServerError, app.ERROR_AUTH_CHECK_TOKEN_FAIL, nil)
		return
	}
	logging.Debug("isExist[%v]", isExist)
	if !isExist {
		appG.Response(http.StatusUnauthorized, app.ERROR_AUTH, nil)
		return
	}

	logging.Info("GenerateToken ...")
	token, err := encryption.GenerateToken(username, password)
	if err != nil {
		appG.Response(http.StatusInternalServerError, app.ERROR_AUTH_TOKEN, nil)
		return
	}
	logging.Debug("token[%v]", token)

	appG.Response(http.StatusOK, app.SUCCESS, map[string]string{
		"token": token,
	})
}
